from typing import Dict, Optional

from aardwolf.extensions.RDPECLIP.fileprovider import FileProvider
from egg_timer import EggTimer


class InMemoryFileProvider(FileProvider):
    """
    Provides data from files stored in memory to the clipboard
    """

    def __init__(
        self,
        *,
        files: Optional[Dict[str, bytes]] = None,
        timer: Optional[EggTimer] = None,
        timeout: float = 5,
    ):
        self._files: Dict[str, bytes] = {} if files is None else files
        self._timer = EggTimer() if timer is None else timer
        self._timeout = timeout

    def set_files(self, files: Dict[str, bytes]):
        self._files.clear()
        self._files.update(files)

    def get_file_data(self, name: str, start: int, count: int) -> bytes:
        self._timer.set(timeout_sec=self._timeout)
        return self._files[name][start : start + count]

    def is_download_active(self) -> int:
        return not self._timer.is_expired()

    def get_file_size(self, name: str) -> int:
        return len(self._files[name])

    def __deepcopy__(self, _):
        # Normally a deepcopy would create a deep copy of all members. However, we don't want to
        # actually perform a deep copy here, since we want to share the _files dictionary between
        # instances. This would allow us to create an instance of this class, pass it to the
        # clipboard (which is itself deep copied), and have any changes made to our instance be
        # reflected in the one held by the clipboard.
        return InMemoryFileProvider(files=self._files, timer=self._timer, timeout=self._timeout)
